const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

// 确保 uploads 目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
    console.log('✓ uploads 目录已创建');
}

// 中间件配置
app.use(cors());
app.use(bodyParser());

// 静态文件服务 - 提供uploads目录的文件访问
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(uploadsDir, ctx.path.replace('/uploads/', ''));
        if (fs.existsSync(filePath)) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 静态文件服务 - 提供static目录的文件访问（用于本地音频文件）
const staticDir = path.join(__dirname, '..', 'static');
console.log('静态文件目录:', staticDir);
console.log('静态文件是否存在:', fs.existsSync(staticDir));
if (fs.existsSync(staticDir)) {
    console.log('静态文件列表:', fs.readdirSync(staticDir));
}

app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/static/')) {
        const filePath = path.join(staticDir, ctx.path.replace('/static/', ''));
        console.log('请求静态文件:', ctx.path, '-> 文件路径:', filePath, '存在:', fs.existsSync(filePath));
        if (fs.existsSync(filePath)) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 文件上传配置
const upload = multer({
    dest: uploadsDir,
    limits: { 
        fileSize: 50 * 1024 * 1024 // 50MB
    },
    fileFilter: (req, file, cb) => {
        const allowedTypes = ['audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac', 'audio/flac', 'audio/x-m4a'];
        if (allowedTypes.includes(file.mimetype)) {
            cb(null, true);
        } else {
            cb(new Error('不支持的文件格式'), false);
        }
    }
});

// 上传音频文件路由
router.post('/api/upload/audio', upload.single('audio'), async (ctx) => {
    try {
        console.log('收到上传请求');
        
        if (!ctx.file) {
            ctx.status = 400;
            ctx.body = {
                code: -1,
                message: '没有收到文件'
            };
            return;
        }

        const file = ctx.file;
        console.log('文件信息:', {
            originalname: file.originalname,
            mimetype: file.mimetype,
            size: file.size,
            filename: file.filename
        });

        // 生成新的文件名（保持原扩展名）
        const ext = path.extname(file.originalname);
        const newFilename = file.filename + ext;
        const oldPath = file.path;
        const newPath = path.join(uploadsDir, newFilename);

        // 重命名文件
        fs.renameSync(oldPath, newPath);
        console.log('文件已保存:', newPath);

        ctx.body = {
            code: 0,
            message: '上传成功',
            data: {
                filename: newFilename,
                originalname: file.originalname,
                size: file.size,
                url: `http://localhost:3000/uploads/${newFilename}`
            }
        };
    } catch (error) {
        console.error('上传失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: -1,
            message: '上传失败: ' + error.message
        };
    }
});

// 健康检查
router.get('/health', async (ctx) => {
    ctx.body = { status: 'ok', message: '服务器运行正常' };
});

// 根路由
router.get('/', async (ctx) => {
    ctx.body = { message: '音乐服务器运行中', version: '1.0.0' };
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 启动服务器
const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
    console.log(`🎵 音乐服务器已启动`);
    console.log(`📡 服务器地址: http://localhost:${PORT}`);
    console.log(`📁 上传目录: ${uploadsDir}`);
    console.log(`📁 静态目录: ${staticDir}`);
    console.log(`🚀 上传接口: http://localhost:${PORT}/api/upload/audio`);
    console.log(`🎵 静态音频: http://localhost:${PORT}/static/brightest_star.mp3`);
});